package com.zhuoli.zblog.service.impl;

import com.google.common.collect.Lists;
import com.zhuoli.zblog.repository.model.User;
import com.zhuoli.zblog.repository.model.UserRole;
import com.zhuoli.zblog.repository.service.RoleDaoRepository;
import com.zhuoli.zblog.repository.service.UserDaoRepository;
import com.zhuoli.zblog.repository.service.UserRoleDaoRepository;
import com.zhuoli.zblog.service.LightSwordUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author: zhuoli
 * Description:
 * Date: 上午10:37 2018/4/22
 */
@Service
public class LightSwordUserDetailServiceImpl implements LightSwordUserDetailService {

    @Autowired
    private UserDaoRepository userDaoRepository;

    @Autowired
    private RoleDaoRepository roleDaoRepository;

    @Autowired
    private UserRoleDaoRepository userRoleDaoRepository;

    @Override
    public UserDetails loadUserByUsername(String userPhone) throws UsernameNotFoundException {
        User user = userDaoRepository.queryUserByUserPhone(userPhone);
        if (user == null) {
            throw new UsernameNotFoundException(userPhone + " not found");
        }

        final List<SimpleGrantedAuthority> simpleGrantedAuthorityList = Lists.newArrayList();

        List<UserRole> userRoleList = userRoleDaoRepository.queryUserRoleByUserId(user.getId());

        userRoleList.forEach(ele ->{
            simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(roleDaoRepository.queryRoleById(ele.getRoleId()).getRoleName()));
        });

        return new org.springframework.security.core.userdetails.User(userPhone, user.getUserPwd(), simpleGrantedAuthorityList);
    }
}
